﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GAE_PI.Models;
using GAE_PI.Exceptions;
using System.Xml;
using Fonet;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.IO;
using Fonet.Pdf;

namespace GAE_PI.Controllers
{
    public class MesActivitesController : Controller
    {
        //
        // GET: /MesActivite/

        public ActionResult MesActivites()
        {
            try
            {
                List<View_ActiviteEleve> list = DBModel.getDBM().getActiviteCurrentEleve();
                return View(list);
            }
            catch (GAEException ex)
            {
                ex.errorModel.ControllerName = "MesActivites";
                ex.errorModel.ControllerAction = "MesActivites";
                return View("Error", ex.errorModel);
            }
        }
        /// <summary>
        /// Génère un PDF pour les activités de l'élèves. Fait une requête dans la base de données
        /// </summary>
        /// <returns>Le fichier PDF sous forme de stream</returns>
        public ActionResult ImprimerPDF()
        {
            List<View_ActiviteEleve> list = DBModel.getDBM().getActiviteCurrentEleve();
            if (list.Count == 0) return RedirectToAction("MesActivites");
            XslTransform xslt = new XslTransform();
            //Load the stylesheet.
            Server.MapPath(".");
            xslt.Load(Server.MapPath("~")+"/bin/mesactivites.fo");
            XmlElement s =  DBModel.getDBM().createXML(list);
            XmlNodeReader xnr = new XmlNodeReader(s);
           // System.Diagnostics.Debug.WriteLine(s.OuterXml);
            XPathDocument mydata = new XPathDocument(xnr);
            //Transform the data and send the output to the console.
            XmlReader fofile = xslt.Transform(mydata,null);
            MemoryStream m = new MemoryStream();
            FonetDriver driver = FonetDriver.Make();
            driver.Render(fofile, m);
            MemoryStream pdf =  new MemoryStream(m.ToArray());
            return File(pdf, "application/pdf", "activites_" + list.First().username +"_"+ DBModel.getDBM().getSelectedDate().ToShortDateString()+".pdf");
        }




    }
}
